package org.nuonuo.sdk.client;


import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.nuonuo.sdk.exception.NException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 * @Version 1.0
 * @Author az
 * @Date 2024-03-28 11:05:33
 * @ClassName ModuleHttp
 * @Description
 */
final class ModuleHttp {
    public static final String PROXY_HOST = "proxyHost";
    public static final String PROXY_PORT = "proxyPort";

    ModuleHttp() {
    }

    static String sendSyncHttp(String url, Map<String, String> header, String body, int... timeout) throws IOException {
        HttpHost proxy = null;
        if (header.containsKey("proxyHost") && header.containsKey("proxyPort")) {
            proxy = new HttpHost(header.get("proxyHost"), Integer.parseInt(header.get("proxyPort")), "http");
        }

        HttpPost httpPost = new HttpPost(url);
        HttpConnPool.setRequestConfig(httpPost, proxy, timeout);
        setHeaders(httpPost, header);
        httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8.name()));
        CloseableHttpResponse response = HttpConnPool.getHttpClient(url).execute(httpPost, HttpClientContext.create());
        HttpEntity entity = response.getEntity();
        String result = null;
        int code = response.getStatusLine().getStatusCode();
        if (entity != null) {
            result = EntityUtils.toString(entity, Consts.UTF_8);
        }

        EntityUtils.consume(entity);
        response.close();
        if (code != 200) {
            throw new NException("发送HTTP请求失败 code=" + code + " result=" + result);
        } else {
            return result;
        }
    }

    private static void setHeaders(HttpPost httpPost, Map<String, String> header) {
        Set<String> keys = header.keySet();
        Iterator i$ = keys.iterator();

        while(i$.hasNext()) {
            String key = (String)i$.next();
            httpPost.addHeader(key, (String)header.get(key));
        }

    }
}

